#include "qlagerwidget.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDesktopWidget>
#include "chelperclass.h"

QLagerWidget::QLagerWidget(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,m_selectedText("") 
    ,m_selectedTextName("")
	,m_offset(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
	connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(lineEditClicked()));
	connect(ui.radioButton, SIGNAL(clicked()), this, SLOT(radioButtonClicked()));
	connect(ui.radioButton_2, SIGNAL(clicked()), this, SLOT(radioButtonClicked()));
	connect(ui.prevButton, SIGNAL(clicked()), this, SLOT(prevButtonPressed()));
	connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextButtonPressed()));

	ui.radioButton->setChecked(true);
    listaAll("%");
}

QLagerWidget::~QLagerWidget()
{

}
void QLagerWidget::prevButtonPressed()
{
	m_offset = m_offset <= 70 ? 0 : m_offset - 70;
	listaAll(ui.lineEdit->text());
}


void QLagerWidget::nextButtonPressed()
{
	m_offset += 70;
	listaAll(ui.lineEdit->text());
}

void QLagerWidget::radioButtonClicked()
{
	m_offset = 0;
	listaAll(ui.lineEdit->text());
}

void QLagerWidget::pressEscape()
{
    emit closeW();
}

void QLagerWidget::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}

void QLagerWidget::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}


void QLagerWidget::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
        emit sLagerToDokument(m_selectedText, m_selectedTextName, m_selectedTextNameSaldo, m_selectedMagTip);	
	}
}

void QLagerWidget::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QLagerWidget::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedTextName = model->item(i, 1) ? model->item(i, 1)->text():"";
    m_selectedTextNameSaldo = model->item(i, 5) ? model->item(i, 5)->text():"";
	m_selectedMagTip = model->item(i, 7) ? model->item(i, 7)->text():"";
}

void QLagerWidget::listaAll(const QString& nameSearch)
{
	QLocale loc;
	int mag_id = 1;
	QString tempLimit = "";

	int r = 0;
	int c = 8;
	int fieldNo[8];
	QString country[8];
	int colWidth[] = {50, 250, 80, 180, 90, 90, 90, 90};
	QString colName[7] = {"id", "artikal", "edm", "proizvoditel", "sum(vkol)", "sum(ikol)", "sum(vkol)-sum(ikol)"};
	QString tempWhere = "";
	if (ui.radioButton->isChecked())
	{
		tempWhere =" artikli.artikal like '%" + nameSearch + "%' limit 70 OFFSET "+ QString::number(m_offset, 10);
	}
	else
	{
		tempWhere =" artikli.proizvoditel like '%" + nameSearch + "%' limit 70 OFFSET "+ QString::number(m_offset, 10);
	}

	QString temp = "";
	temp = "select distinct artikli.sifra ,artikli.artikal, artikli.edm, artikli.proizvoditel, artikli.id, mag_id "
		"from magacin "
		"left join artikli on  magacin.artikal_id = artikli.id "
		"where (magacin.dok_tip = 20 or magacin.dok_tip = 22 or magacin.dok_tip = 24 or "
		" magacin.dok_tip = 40 or magacin.dok_tip = 41 or magacin.dok_tip = 44) and " +
		tempWhere;

	QSqlQuery query(temp);
	QSqlError err = query.lastError();
	model = new QStandardItemModel(r, c);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра"));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Артикал"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Едм"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Производител"));

	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Влез. Кол."));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Изл. Кол."));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Салдо"));
	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);

	ui.tableView->setHorizontalHeader(header);
	header->show();
	int row = 0;
	CHelperClass chc(this);
	float vkVlezKol = 0.f;
	float vkIzlezKol = 0.f;
	float vkSaldo = 0.f;
	setUpdatesEnabled(false);
	chc.createSaldoMapAll();
	int iaaa = 0;
	while (query.next()) 
	{
		if (iaaa == 200)
		{
			break;
		}
		iaaa++;
		for (int i = 0; i < c; i++)
		{
			QString temp = query.value(i).toString();
			QStandardItem *item = NULL; 

			if (i == 4)
			{
				vkVlezKol = chc.getLagerListaAll(query.value(4).toString() , (QString)"PRILIV", query.value(5).toString());
				temp =  loc.toString(vkVlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 5)
			{
				vkIzlezKol = chc.getLagerListaAll(query.value(4).toString() , (QString)"ODLIV", query.value(5).toString());
				temp =  loc.toString(vkIzlezKol ,'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 6)
			{
				vkSaldo = vkVlezKol - vkIzlezKol;
				temp =  loc.toString(vkSaldo ,'f',2);
				item = new QStandardItem(temp);
				QBrush newBrush;
				if (vkSaldo < 0)
				{
					newBrush.setColor(Qt::darkRed);
					item->setForeground(newBrush);
				}
				else if (vkSaldo == 0)
				{
					newBrush.setColor(Qt::black);
					item->setForeground(newBrush);
				}
				else
				{
					newBrush.setColor(Qt::darkGreen);
					item->setForeground(newBrush);
				}
				item->setTextAlignment(Qt::AlignRight);
			}
			else if (i == 7)
			{
				switch (query.value(5).toInt())
				{
				case 0:	temp =  trUtf8("АРТИКЛИ"); break;
				case 1:	temp =  trUtf8("ТРГОВСКА РОБА"); break;
				case 2:	temp =  trUtf8("ПРОИЗВОДИ"); break;
				}
				
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else
			{
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}
		row++;
	} 
	setUpdatesEnabled(true);

	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
}

void QLagerWidget::lineEditClicked()
{
	m_offset = 0;
	listaAll(ui.lineEdit->text());
}
